package com.parenting.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.parenting.entities.CommodityDO;
import com.parenting.enums.ResultEnum;
import com.parenting.exception.BaseException;
import com.parenting.mapper.CommodityMapper;
import com.parenting.model.IMPage;
import com.parenting.request.AddCommodityRequest;
import com.parenting.request.SearchCommodityRequest;
import com.parenting.request.UpdateCommodityRequest;
import com.parenting.request.UpdateStockRequest;
import com.parenting.response.CommodityListResponse;
import com.parenting.response.CommodityResponse;
import com.parenting.service.CommodityService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 商品信息表 服务实现类
 * </p>
 *
 * @author 烟台业达-王世玺
 * @since 2021-08-27
 */
@Slf4j
@Service
public class CommodityServiceImpl extends ServiceImpl<CommodityMapper, CommodityDO> implements CommodityService {

    @Autowired
    private RedissonClient redissonClient;

    @Override
    public void addCommodity(AddCommodityRequest request, String shopId) {
        Date date=new Date();
        CommodityDO commodityDO = BeanUtil.copyProperties(request, CommodityDO.class);
        commodityDO.setUpdateDate(date);
        commodityDO.setCreateDate(date);
        commodityDO.setShopId(shopId);
        baseMapper.insert(commodityDO);
    }

    @Override
    public synchronized void updateCommodity(UpdateCommodityRequest request) {
        String lockKey = "lock:commodity:"+request.getId();
        RLock rLock = redissonClient.getLock(lockKey);
        rLock.lock(5, TimeUnit.SECONDS);
        try {
            CommodityDO commodityDO = BeanUtil.copyProperties(request, CommodityDO.class);
            commodityDO.setUpdateDate(new Date());
            baseMapper.updateById(commodityDO);
        }finally{
            rLock.unlock();
            log.info("解锁成功");
        }
    }

    @Override
    public void deleteCommodity(List<String> id) {


        baseMapper.deleteCommodity(id);
    }

    @Override
    public   IMPage<CommodityListResponse>getCommodityListByCondition(SearchCommodityRequest request) {
        log.info("getCommodityListByCondition  request  ===  {}" ,request.toString());
        //是否上架（1上架，2下架）
//        if (null!=request.getShelves()&&request.getShelves()>0){
//            request.setShelves(1);
//        }
        //是否删除（1否，2是 默认 1）
        if (null==request.getCommodityRemove()||request.getCommodityRemove()!=2){
            request.setCommodityRemove(1);
        }
        IPage<CommodityListResponse> commodityListByCondition = baseMapper.getCommodityListByCondition(request.getPage(), request);
        log.info("getCommodityListByCondition  request  ===  {}" ,commodityListByCondition.toString());
        IMPage<CommodityListResponse> commodityListResponseIMPage = new IMPage<>();
        commodityListResponseIMPage.setTotal(commodityListByCondition.getTotal());
        commodityListResponseIMPage.setCurrent(commodityListByCondition.getCurrent());
        commodityListResponseIMPage.setRecords(commodityListByCondition.getRecords());
        commodityListResponseIMPage.setSize(commodityListByCondition.getSize());
        return commodityListResponseIMPage;
    }


    @Override
    public CommodityResponse getCommodityByCommodityId(String commodityId) {
        CommodityDO commodityDO = baseMapper.selectById(commodityId);
        CommodityResponse commodityResponse = BeanUtil.copyProperties(commodityDO, CommodityResponse.class);
        return commodityResponse;
    }


    @Override
    public synchronized void updateStock(UpdateStockRequest request) {
        String lockKey = "lock:updateStock:"+request.getCommodityId();
        RLock rLock = redissonClient.getLock(lockKey);
        rLock.lock(5, TimeUnit.SECONDS);
        try {
            CommodityDO commodityDO = baseMapper.selectById(request.getCommodityId());
            commodityDO.setStock(request.getStock());
           // 操作类型 类型 1、加库存 2、减库存
//            if (request.getType()==1){
//                commodityDO.setStock(commodityDO.getStock()+request.getStock());
//            }
//            if (commodityDO.getStock()>=request.getStock()&&request.getType()==2){
//                commodityDO.setStock(commodityDO.getStock()-request.getStock());
//            }
            commodityDO.setUpdateDate(new Date());
            baseMapper.updateById(commodityDO);
        }finally{
            rLock.unlock();
            log.info("解锁成功");
        }
    }

    @Override
    public void updateStockBy(String commodityId, int number) {
        String lockKey = "lock:updateStock:"+commodityId;
        RLock rLock = redissonClient.getLock(lockKey);
        rLock.lock(5, TimeUnit.SECONDS);
        try {
            CommodityDO commodityDO = baseMapper.selectById(commodityId);
            Integer stock = commodityDO.getStock();
            if(stock<=number){
                throw new BaseException(ResultEnum.COMMODITY_NO_STOCK);
            }
            commodityDO.setStock(stock-number);
            commodityDO.setUpdateDate(new Date());
            baseMapper.updateById(commodityDO);
        }finally{
            rLock.unlock();
            log.info("解锁成功");
        }
    }

    @Override
    public     List<CommodityDO> getCommodityDropDown(String shopId) {

        return  baseMapper.selectList(new LambdaQueryWrapper<CommodityDO>().eq(CommodityDO::getShopId,shopId));
    }


}
